package com.woshua.vpimage

import android.annotation.SuppressLint
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v4.view.ViewPager
import android.widget.ImageView
import com.woshua.vpimage.adapter.MyPageAdapter
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

class MainActivity : AppCompatActivity(), ViewPager.OnPageChangeListener {

    private var curponsition:Int=1
    private var oldPosition:Int=0

    override fun onPageScrollStateChanged(state: Int) {
        if(state==ViewPager.SCROLL_STATE_IDLE)
        {
//            if(curponsition==0)
//            {
//                vp_content.setCurrentItem(adapter.count-2, false)
//            }
//            else if(curponsition==adapter.count-1)
//            {
//                vp_content.setCurrentItem(1, false)
//            }
            vp_content.setCurrentItem(curponsition,false)
        }
    }

    override fun onPageScrolled(p0: Int, p1: Float, p2: Int) {
    }

    override fun onPageSelected(position: Int) {
//        curponsition=position
//
//        when(position){
//            0,3->setSelect(2)
//            1,4->setSelect(0)
//            2->setSelect(1)
//            else->{}
//        }

        curponsition = when(position)
        {
            0-> adapter.count-2
            adapter.count-1-> 1
            else-> position
        }

        mPoints[oldPosition].isSelected=false
        mPoints[curponsition-1].isSelected=true
        oldPosition=curponsition-1
    }

//    mapIndexed高阶函数使用,简化开发
//    private fun setSelect(pos: Int) {
//        mPoints.mapIndexed { index, imageView -> imageView.isSelected=index==pos}
//    }

    private val mPoints: Array<ImageView> by lazy { arrayOf(iv_one, iv_two, iv_three) }

    private lateinit var adapter:MyPageAdapter

    private val handler = Handler {
        if(it.what==10086)
        {
            vp_content.setCurrentItem(it.arg1, true)
        }
        false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mPoints[0].isSelected = true

        adapter=MyPageAdapter()
        vp_content.adapter= adapter
        vp_content.setCurrentItem(curponsition,false)

        vp_content.addOnPageChangeListener(this)

        Timer().schedule(object :TimerTask(){
            override fun run() {
                val message= Message.obtain()
                message.what=10086
                message.arg1=++curponsition
                handler.sendMessage(message)
            }
        },3000, 3000)
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
    }
}
